#encoding: utf-8
from apps.forms import BaseForm
from wtforms import StringField
from wtforms.validators import regexp, InputRequired
import hashlib

# 加签名
class SMSCaptchaForm(BaseForm):
    salt = '%&^&@2321dfgd*&9fgerdfiosjdgkhpererw*^&8574'
    telephone = StringField(validators=[regexp(r'1[2-9]\d{9}')])
    timestamp = StringField(validators=[regexp(r'\d{13}')])
    sign = StringField(validators=[InputRequired()])

    def validate(self):
        result = super(SMSCaptchaForm, self).validate()
        if not result:
            return False
        telephone = self.telephone.data
        timestamp = self.timestamp.data
        sign = self.sign.data

        # md5(timestamp+telephone+salt)
        # md5函数必须传递一个bytes类型的字符串做为参数
        signOK = hashlib.md5((timestamp + telephone + self.salt).encode('utf-8')).hexdigest()
        if sign == signOK:
            return True
        else:
            return False

